package com.google.rui.demos.camera.demos;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.rui.demos.R;
import com.google.rui.utils.AndroidUtils;

public class CameraIntentActivity  extends Activity {
	private final static int Carm_ID = 1001; // 拍照
	private final static int Video_ID = 1002; // 录像
	private final static int MEDIA_TYPE_IMAGE = 1003;
	private final static int MEDIA_TYPE_VIDEO = 1004;
	private String mMediaPath = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera_main);
		 Button captureButton = (Button) findViewById(R.id.button_takepic);
	        captureButton.setOnClickListener(
	            new View.OnClickListener() {
	                @Override
	                public void onClick(View v) {
	                    // get an image from the camera
	                  showCarm(MEDIA_TYPE_IMAGE);
	                }
	            }
	        );
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {

		case Carm_ID:
			if (resultCode == RESULT_OK) {
				
				if (mMediaPath == null || mMediaPath.equals("")){
					Toast.makeText(this, "未发现图片路径"+ mMediaPath, Toast.LENGTH_LONG).show();
					return;
				}
				
				// ************************压缩图片**************

				Bitmap bm = BitmapFactory.decodeFile(mMediaPath); // 原始图片
				File oriBm = new File(mMediaPath);
				long oribmSize = oriBm.length();
				
				// 判断bitmap占用空间是否大于允许最大空间， 如果大于则压缩 小于则不压缩
				if (oribmSize > 0) {
					
					System.out.println("图片原始大小:" +Formatter.formatFileSize(CameraIntentActivity.this, oribmSize));
					
					// 动态计算出图片的inSampleSize
					BitmapFactory.Options opts = new BitmapFactory.Options();
					opts.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(mMediaPath, opts);
					opts.inSampleSize = ImageCoderPaser.computeSampleSize(opts, -1,
							320 * 240);
					opts.inJustDecodeBounds = false;
					try {
						bm = BitmapFactory.decodeFile(mMediaPath, opts);
					} catch (OutOfMemoryError err) {

					}
					/////////////////////////////
//					long scale = oribmSize / IMAGE_MAX_SIZE; // 压缩倍数
//					bm = ImageCoderPaser.zoomImage(bm,
//							bm.getWidth() / Math.sqrt(scale), bm.getHeight()
//									/ Math.sqrt(scale));
					//////////////////////////
					 //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）  
	                ByteArrayOutputStream baos = new ByteArrayOutputStream();
	                bm.compress(Bitmap.CompressFormat.JPEG, 90, baos);
	                byte[] b = baos.toByteArray();
	                //将字节换成KB
					
					System.out.println("图片压缩后大小:" +Formatter.formatFileSize(CameraIntentActivity.this, b.length));
					// 保存压缩后图片
					mMediaPath = mMediaPath.replace(".jpg", "_s.jpg"); // 重命名压缩文件
					FileOutputStream out = null;
					File file = new File(mMediaPath);
					Log.e("After :","压缩后大小："+ Formatter.formatFileSize(CameraIntentActivity.this, file.length()));
					try {
						out = new FileOutputStream(file);
						if (bm.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
							out.flush();
							out.close();
						}
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catchblock
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catchblock
						e.printStackTrace();
					} finally {
						try {
							if (out != null)
								out.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}
			
			}
			break;

		case Video_ID:

			if (resultCode == Activity.RESULT_OK) {
				if (mMediaPath == null || mMediaPath.equals(""))
					return;
				InputStream in = null;
				OutputStream out = null;
				File file = new File(mMediaPath);
				if (!file.exists()) {
					try {
						Bundle bundle = data.getExtras();
						AssetFileDescriptor videoAsset = getContentResolver()
								.openAssetFileDescriptor(data.getData(), "r");
						in = videoAsset.createInputStream();
						out = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int len;
						while ((len = in.read(buf)) > 0) {
							out.write(buf, 0, len);
						}
						in.close();
						out.close();

					} catch (Exception e) {
						Log.d(this.getClass().getSimpleName(), "无法保存录像");
						Toast.makeText(this, "faile to save video file",
								Toast.LENGTH_SHORT).show();
						mMediaPath = ""; // 放弃录像
						return;
					} finally {
						try {
							if (in != null)
								in.close();
							if (out != null)
								out.close();
						} catch (Exception e2) {
							// TODO: handle exception
							e2.printStackTrace();
						}
					}
				}
				
			}
			break;
		default:
			break;
		}
	}

       
	
  
   
 // 调用拍照
	private void showCarm(int mediaType) {
		// 判断是否有存储卡
		if (!AndroidUtils.hasSDCard()) {
			/* 提醒User未安装存储卡 */
			Toast.makeText(this,
					"无存储卡",
					Toast.LENGTH_SHORT).show();
			return;
		}

		String mediaPath = getMeidaFileName(mediaType);
		
		
		mMediaPath = mediaPath;
		if (mediaType == MEDIA_TYPE_IMAGE) {
			if (mediaPath == null || mediaPath.equals("")) {/* 提醒 */
				Toast.makeText(this, "无法创建存储照片路径!", Toast.LENGTH_SHORT).show();
				return;
			}
			// 调用系统拍照
			Intent imageCaptureIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(mediaPath)));
			startActivityForResult(imageCaptureIntent, Carm_ID);

		} else if (mediaType == MEDIA_TYPE_VIDEO) {
			if (mediaPath == null || mediaPath.equals("")) {/* 提醒 */
				Toast.makeText(this, "无法创建存储录像路径!", Toast.LENGTH_SHORT).show();
				return;
			}
			// 调用系统录像
			Intent videoCaptureIntent = new Intent(
					MediaStore.ACTION_VIDEO_CAPTURE);
			// 一些机型不支持谁知视频名称和路径，如三星i9100，对于视频的路径处理在OnAtcivityResult()处处理
			// videoCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new
			// File(mediaPath)));
			videoCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.8);
			// videoCaptureIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT,5*1024);
			// //限制大小2.2以上支持
			startActivityForResult(videoCaptureIntent, Video_ID);

		}

	}

	// 生成文件名称
	private String getMeidaFileName(int mediaType) {
		DateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String tempfilename = format.format(Calendar.getInstance().getTime());
		File file = new File(getOutputMediaFile(this,mediaType));
		if (!file.exists()) {
			file.mkdirs();
		}
		if (mediaType == MEDIA_TYPE_IMAGE) {
			return file.getAbsolutePath() + File.separator + "tempfilename"
					+ ".jpg";
		} else if (mediaType == MEDIA_TYPE_VIDEO) {
			return file.getAbsolutePath() + File.separator + tempfilename
					+ ".mp4";
		}

		return "";
	}

	/**
	 * 多媒体文件保存位置
	 * 
	 * @return
	 */
	public static String getOutputMediaFile(Context c,int type) {
		
			File dir = Environment.getExternalStorageDirectory();
			File file = null;
			String mediaStorageDir = "Media";
			if (type == MEDIA_TYPE_IMAGE) {
				file = new File(dir,mediaStorageDir + File.separator + "Images");
			} else if (type == MEDIA_TYPE_VIDEO) {
				file = new File(dir, mediaStorageDir+ File.separator + "Videos");
			}
			if (!file.exists()) {
				file.mkdirs();
			}
			return file.getAbsolutePath();
		
	}

}
